#coding:utf-8
'''
* coder  : Dzlua
* email  : 505544956@qq.com
* module : api-frame
* path   : app/utils
* file   : generate.py
* time   : 2017/10/21
'''
#--------------------#
from base import choice_input, get_input
import base
#----------#
from datetime import datetime
#--------------------#

#--------------------#
def apply_templete(info, templete):
    try:
        text = templete
        for k,v in info.items():
            text = text.replace('{{'+k+'}}', v)
        return text
    except:
        pass
    return ''
#----------#
def make_content(infos, quiet=False):
    content = ''
    for v in infos:
        content += v['key'] + ' = '

        data = v['default']
        if not quiet:
            tip = v['key'] + ':'
            try:
                data = v['action'](v, tip)
            except:
                data = get_input(tip, default=v['default'])
        #                                

        content += data + '\r\n'
    content += '\r\n#--------------------#\r\n'
    return content
#--------------------#

#--------------------#
def _get_file_content(info):
    content = """#coding:utf-8
'''
* coder  : {{coder}}
* email  : {{email}}
* module : {{module}}
* path   : {{path}}
* file   : {{file}}
* time   : {{time}}
'''
#--------------------#
#--------------------#
"""
    data = {
        'coder': info['coder'] or 'coder',
        'email': info['email'] or 'email',
        'module': info['module'] or 'module',
        'path': info['path'] or 'path',
        'file': info['file'] or 'file',
        'time': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
    }

    return apply_templete(data, content)
#----------#
def _get_config_content(quiet, info):
    def action_sql_uri(info, tip):
        print(tip)

        uri = ''

        space = 4
        prefix = base.get_space(space)

        tp = choice_input('database type : ',
            choice=['mysql', 'sqlite', 'others'],
            space=space, required=True)
        print(prefix + 'use database ' + tp)

        if tp == 'mysql':
            db = get_input('database name : ', space=space*2, required=True)
            user = get_input('database user: ', space=space*2, required=True)
            pwd = get_input('database password: ', space=space*2, default='')
            host = get_input('database host: ', space=space*2, default='localhost')
            port = get_input('database port: ', space=space*2, default='3306')
            uri = 'mysql://' + user + ':' + pwd + \
                '@' + host + ':' + port + '/' + \
                db + '?charset=utf8'
        else:
            uri = get_input('', space=8, default='') or ''
        print(prefix + uri)
        return "'" + uri + "'"
    #----------#
    content = [
        {
            'key': 'SECRET_KEY',
            'default': "'the quick brown fox jumps over the lazy dog'",
            'tip': 'string'
        }, {
            'key': 'SQLALCHEMY_DATABASE_URI',
            'default': "'mysql://" + info['coder'] + \
                    ':' + info['coder'] + \
                    '@localhost:3306/' + \
                    info['module'] + \
                    "?charset=utf8'",
            'action': action_sql_uri,
            'tip': 'string, uri'
        }, {
            'key': 'SQLALCHEMY_COMMIT_ON_TEARDOWN',
            'default': 'True',
            'tip': 'bool, True/flase'
        }, {
            'key': 'SQLALCHEMY_TRACK_MODIFICATIONS',
            'default': 'True',
            'tip': 'bool, True/false'
        }
    ]
    return make_content(content, quiet)
#--------------------#

#--------------------#
def generate_files(files, quiet=False, getContent=None):
    coder = None
    email = None
    if not quiet:
        coder = get_input('input coder name', '')
        email = get_input('input email', '')

    errors = []

    cur_dir = base.module_dir()
    for f in files:
        data = {
            'coder': coder or 'coder',
            'email': email or 'email',
            'module': base.file_name(cur_dir),
            'path': base.dir_name(f) or '.',
            'file': base.file_name(f),
        }
        full_file = base.file_join(cur_dir, f)
        content = _get_file_content(data)
        if getContent:
            data['full_file'] = full_file
            content += getContent(quiet, data)
        ok = base.create_file(full_file, content)
        if not ok:
            errors.append(f)
    #
    if len(errors) == 0:
        print('Done.')
    else:
        print('Error: %s files error.' % len(errors))
#----------#
def generate_config(quiet=False):
    generate_files(['config.py'], quiet, _get_config_content)
#--------------------#